/*
 * @Author: wangtao
 * @Date: 2021-02-18 11:21:01
 * @LastEditors: kanglang
 * @LastEditTime: 2021-04-29 22:10:45
 * @Description: 保险个人中心
 */
import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  ScrollView,
  RefreshControl,
  ImageBackground,
  BackHandler
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import {
  px2dp,
  mainBgColorLightGray,
  mainBgColorWhite,
  splitLineColorLightGray,
  screenWidth,
  fontColorCoffee,
  fontColorDeepGray,
  isAndroid
} from '@/styles';
import {
  iconUserGoldInsurance,
  iconUserGrayInsurance,
  leftBack,
  defaultman,
  userMark,
  legalManagement,
  userCertification,
  certiCompany,
  GoldDownArrow,
  iconMyApplicationCoffee,
  iconMyPolicyCoffee,
} from '@/images';
import { msg, cache } from '@/common';
import Picker from '@/common/picker';
import userApi from '@/api/user';
import businessApi from '@/api/business';
import RowItem from '../../../components/SimpleRowItem';
import RechargeHeader from '../../../components/RechargeHeader';

export default class InsuranceUser extends React.Component {
    static navigationOptions = () => ({
      title: '我的',
      tabBarIcon: ({ focused }) => (
        <Image
          source={focused ? iconUserGoldInsurance : iconUserGrayInsurance}
          style={{ width: 24, height: 24 }}
        />
      )
    });

    constructor(props) {
      super(props);
      this.state = {
        custLegals: [],
        user: {},
        currentLegal: {},
        currentCustId: '',
        adminState: 0, // 是否通过管理员认证
        isRefreshing: false, // 是否在刷新
      };
    }

    componentDidMount() {
      this.getUserInfo();
      this.getCertiCustList();
      msg.on('updateB2BUser', () => {
        this.getUserInfo();
        this.getCertiCustList();
      });
      if (isAndroid) {
        BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
      }
    }

    componentWillUnmount() {
      msg.off('updateB2BUser');
      if (isAndroid) {
        BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
      }
    }

    getUserInfo = () => {
      userApi.getUserInfo().then(res => {
        if (res.success) {
          this.setState({ user: res.data });
        } else {
          msg.emit('app:tip', { text: '用户信息获取失败' });
        }
      });
    }

    // 获取提交企业的列表
    getCertiCustList = () => {
      businessApi.getCustomLegals().then(res => {
        if (res.success) {
          const curData = res.data;
          if (curData && curData.length > 0) {
            this.setState({
              custLegals: curData,
            }, () => {
              businessApi.getCustRedis().then(resCurLegal => {
                if (resCurLegal.success && resCurLegal.data && JSON.stringify(resCurLegal.data) != '{}') {
                  let tempLegal = [];
                  curData.forEach((item, index) => {
                    tempLegal.push(item.custName);
                  });
                  const isSameLegal = tempLegal.indexOf(resCurLegal.data ? resCurLegal.data.custName : '');
                  if (isSameLegal != -1) {
                    this.setState({
                      currentLegal: curData[isSameLegal],
                      currentCustId: curData[isSameLegal].custId
                    }, () => {
                      this.saveAndGetManagerStatus();
                      this.getIsManager();
                    });
                  } else {
                    this.setState({
                      currentLegal: resCurLegal.data,
                      currentCustId: resCurLegal.data.custId
                    }, () => {
                      this.saveAndGetManagerStatus();
                      this.getIsManager();
                    });
                  }
                } else {
                  this.setState({
                    currentLegal: curData[0],
                    currentCustId: curData[0].custId
                  }, () => {
                    this.saveAndGetManagerStatus();
                    this.getIsManager();
                    this.saveLegalInfo(curData[0]);
                  });
                }
              });
            });
          } else {
            businessApi.getCustRedis().then(resCurLegal => {
              if (resCurLegal.success && resCurLegal.data && JSON.stringify(resCurLegal.data) != '{}') {

              } else {
                this.setState({
                  currentLegal: {},
                  currentCustId: ''
                });
                AsyncStorage.removeItem(
                  cache.CURRENT_LEGAL,
                  (err) => {
                    console.log('清除当前企业缓存异常：', err);
                  }
                );
              }
            });
            this.setState({ custLegals: [] });
          }
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      });
    }

    getIsManager = () => {
      const { currentCustId } = this.state;

      businessApi.getAppAuth({ custId: currentCustId }).then(res => {
        if (res.success) {
          const resData = res.data;
          const isManagerIndex = resData.indexOf('userManagement');
          if (isManagerIndex != -1) {
            this.setState({ isManager: true });
          } else {
            this.setState({ isManager: false });
          }
        } else {
          this.setState({ isManager: false });
        }
      });
    }

    saveAndGetManagerStatus = () => {
      const { currentLegal, currentCustId } = this.state;
      AsyncStorage.setItem(
        cache.CURRENT_LEGAL,
        JSON.stringify(currentLegal),
      );
      this.getLegalManagerStatus(currentCustId);
    }

    refreshControlAction = () => {
      this.getUserInfo();
      this.getCertiCustList();
    }

    render() {
      const { isManager, custLegals, user, currentLegal } = this.state;
      const certiStatus = this.certiStatus();

      return (
        <SafeAreaView style={styles.container}>
          <RechargeHeader
            style={{ backgroundColor: mainBgColorWhite }}
            leftBackStyle={{ backgroundColor: 'rgba(0,0,0,0.1)' }}
            leftBackIcon={leftBack}
            leftTitle='我的'
          />
          <ScrollView
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
            refreshControl={
              // 设置下拉刷新组件
              <RefreshControl
                refreshing={this.state.isRefreshing}
                onRefresh={() => {
                  this.refreshControlAction();
                }}
                tintColor='white'
                title={this.state.isRefreshing ? '刷新中....' : '下拉刷新'}
              />
            }
          >
            <View style={styles.inner}>
              <View style={{ flex: 1, backgroundColor: mainBgColorWhite, paddingVertical: px2dp(32) }}>
                <View style={styles.leftContent}>
                  <Image
                    style={styles.userAvart}
                    source={user.avatarId ? { uri: user.avatarId } : defaultman}
                  />
                  <View style={styles.avartRight}>
                    <View style={styles.nameBox}>
                      <Text style={styles.username}>{user && user.name}</Text>
                      {
                        isManager &&
                        <Image
                          style={styles.isManagerIcon}
                          source={require('../../../images/icons/is_manager_icon.png')}
                        />
                      }
                      {
                        currentLegal.type == 1 &&
                        <Image
                          style={styles.isUserIcon}
                          source={userMark}
                          resizeMode='stretch'
                        />
                      }
                      {
                        (custLegals && custLegals.length > 0) ?
                          <Image
                            style={styles.isCertiIcon}
                            source={require('../../../images/icons/icon_caveat_green.png')}
                          /> :
                          <Image
                            style={styles.isCertiIcon}
                            source={require('../../../images/icons/icon_caveat_gray.png')}
                          />
                      }

                    </View>
                    <Text style={styles.headerDesc}>小马国炬为您保驾护航每一天</Text>

                  </View>
                </View>
                {this.currentLegalView()}
              </View>
              <View style={styles.mt40}>
                <RowItem
                  titleRight={certiStatus.type}
                  rightColor={certiStatus.color}
                  title='用户认证'
                  icon={userCertification}
                  onPress={this.toCerti}
                />
                {/* {isManager &&
                <RowItem
                  title='企业管理'
                  icon={legalManagement}
                  onPress={this.toEnterpriseManage}
                />} */}
              </View>
              <View style={styles.mt40}>

                <RowItem
                  title='我的申请'
                  icon={iconMyApplicationCoffee}
                  onPress={() => {
                    msg.emit('router: goToNext', {
                      routeName: 'InsuranceApplyListMy',
                    });
                  }}
                />
                <RowItem
                  title='我的保单'
                  icon={iconMyPolicyCoffee}
                  onPress={() => {
                    msg.emit('router: goToNext', {
                      routeName: 'InsuranceListMy',
                    });
                  }}
                />
                {/* <RowItem
                                title="我的合同"
                                icon={legalContractManagement}
                                onPress={this.toContractSYSList}
                            /> */}
                {
                  custLegals && custLegals.length > 0 &&
                  <RowItem
                    title='用户注册协议'
                    icon={require('../../../images/icons/icon_protocol.png')}
                    onPress={this.userProtocal}
                    renderSegment={false}
                  />
                }

              </View>
            </View>
          </ScrollView>
        </SafeAreaView>
      );
    }

    onBackAndroid = () => {
      Picker.hide();
      return true;
    };

    // 认证状态
    certiStatus = () => {
      const { custLegals, currentLegal } = this.state;
      if (custLegals && custLegals.length > 0) {
        if (currentLegal.auditState == 1) {
          return {
            type: '已认证',
            color: '#999796'
          };
        }
        if (currentLegal.auditState == 2) {
          return {
            type: '审核失败',
            color: '#EB2F2F'
          };
        }
        if (currentLegal.auditState == 3) {
          return {
            type: '审核中',
            color: '#EF9730'
          };
        }
      }
      return { type: '未认证', color: '#BA914A' };
    }

    // 当前选中企业的view
    currentLegalView = () => {
      const { custLegals, currentLegal } = this.state;
      if (currentLegal.type == 1) return;
      if (custLegals && custLegals.length > 0) {
        return (
          <ImageBackground
            style={styles.userBgImg}
            source={require('../../../images/insurance/insurance_user_bg.png')}
          >
            <TouchableOpacity
              activeOpacity={0.8}
              style={[styles.certiBox]}
              onPress={this.changeBusiness}
            >
              <Image
                style={styles.noCertiIcon}
                source={certiCompany}
              />
              <View style={{ flex: 1 }}>
                <Text style={styles.onCertiTxt}>{currentLegal.custName}</Text>
              </View>
              <Image
                style={styles.busRightDown}
                source={GoldDownArrow}
              />
            </TouchableOpacity>
          </ImageBackground>
        );
      }
    }

    refreshControlAction = () => {
      this.getUserInfo();
      this.getCertiCustList();
    }

    changeBusiness = () => {
      const { custLegals } = this.state;
      let pickerL = [];
      custLegals.map((item) => {
        pickerL.push(item.custName);
      });
      this.showPicker('切换企业', pickerL);
    }

    showPicker = (title, dataList) => {
      const { custLegals, currentCustId } = this.state;
      let currentName = '';
      custLegals.map((item, index) => {
        if (item.custId == currentCustId) {
          currentName = item.custName;
        }
      });
      Picker.init({
        pickerTitleText: title,
        pickerCancelBtnText: '取消',
        pickerConfirmBtnColor: [186, 145, 74, 1],
        pickerCancelBtnColor: [102, 101, 100, 1],
        pickerConfirmBtnText: '确定',
        selectedValue: [currentName],
        pickerBg: [255, 255, 255, 1],
        pickerToolBarBg: [255, 255, 255, 1],
        pickerFontColor: [186, 145, 74, 1],
        pickerRowHeight: 40,
        pickerData: dataList,
        onPickerConfirm: (pickedValue, pickedIndex) => {
          custLegals.forEach(item => {
            if (item.custName == pickedValue.toString()) {
              this.setState({ currentCustId: item.custId, currentLegal: item }, () => {
                const { currentCustId, currentLegal } = this.state;
                this.getLegalManagerStatus(currentCustId);
                this.saveLegalInfo(currentLegal);
                this.getIsManager();
                msg.emit('router: refreshRoute', {
                  routeName: 'B2BMallTab',
                });
              });
            }
          });
        },
        onPickerCancel: (pickedValue, pickedIndex) => {
          Picker.hide();
        },
        onPickerSelect: (pickedValue, pickedIndex) => {
        },
      });
      Picker.show();
    };

    // 去认证/已认证查看
    toCerti = () => {
      const { custLegals, currentLegal } = this.state;
      if (custLegals && custLegals.length > 0) { // 已认证
        if (currentLegal.type == 1) { // 个人
          msg.emit('router: goToNext', {
            routeName: 'PersonCertification',
            checkType: 'view'
          });
        } else if (currentLegal.type == 2) { // 企业
          msg.emit('router: goToNext', {
            routeName: 'BusinessData',
            custId: currentLegal.custId,
            routerFrom: 'Insurance'
          });
        }
      } else { // 未认证 需要选择个人/企业
        let selectArr = ['个人'];
        this.selectAuthType('选择认证类型', selectArr);
      }
    }

    selectAuthType = (title, dataList) => {
      Picker.init({
        pickerTitleText: title,
        pickerCancelBtnText: '取消',
        pickerConfirmBtnColor: [186, 145, 74, 1],
        pickerCancelBtnColor: [102, 101, 100, 1],
        pickerConfirmBtnText: '确定',
        selectedValue: [],
        pickerBg: [255, 255, 255, 1],
        pickerToolBarBg: [255, 255, 255, 1],
        pickerFontColor: [186, 145, 74, 1],
        pickerRowHeight: 40,
        pickerData: dataList,
        onPickerConfirm: (pickedValue, pickedIndex) => {
          if (pickedValue == '个人') {
            msg.emit('router: goToNext', {
              routeName: 'PersonCertification',
              checkType: 'add'
            });
          } else if (pickedValue == '企业') {
            msg.emit('router: goToNext', {
              routeName: 'CertiKnow',
              routerFrom: 'Insurance'
            });
          }
        },
        onPickerCancel: (pickedValue, pickedIndex) => {
        },
        onPickerSelect: (pickedValue, pickedIndex) => {
        },
      });
      Picker.show();
    }

    wlProtocal = () => {
      const { currentCustId } = this.state;
      msg.emit('router: goToNext', {
        routeName: 'B2BMallAddressList',
        custId: currentCustId
      });
    }

    userProtocal = () => {
      const { currentLegal } = this.state;
      if (currentLegal.type == 1) { // 个人
        msg.emit('router: goToNext', {
          routeName: 'CustAgreement',
          routerFrom: 'PersonCertAgreement'
        });
      } else if (currentLegal.type == 2) { // 企业
        msg.emit('router: goToNext', {
          routeName: 'CustAgreement',
          routerFrom: 'businessRegisterAgreement'
        });
      }
    }

    toEnterpriseManage = () => {
      const { currentCustId, currentLegal } = this.state;
      // 跳转企业管理
      msg.emit('router: goToNext', {
        routeName: 'B2BMallEnterpriseManage',
        custId: currentCustId,
        legal: currentLegal,
        routerFrom: 'Insurance'
      });
    }

    toContractSYSList = () => {
      // 跳转合同
      msg.emit('router: goToNext', {
        routeName: 'B2BContractList'
      });
    }

    // 获取用户在该企业下是否是管理员的状态
    getLegalManagerStatus = (custId) => {
      businessApi.getLegalState({ custId }).then(res => {
        if (res.success && res.data) {
          this.setState({
            adminState: res.data.adminState
          });
        }
      });
    }

    saveLegalInfo = (vo) => {
      businessApi.saveCustRedis({ ...vo }).then(res => {
        if (res.success) {
          AsyncStorage.setItem(
            cache.CURRENT_LEGAL,
            JSON.stringify(vo)
          );
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      });
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  headerBox: {
    flexDirection: 'row',
    // justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    justifyContent: 'flex-end'
  },
  userAvart: {
    width: px2dp(135),
    height: px2dp(135),
    borderRadius: px2dp(135) * 2,
    marginLeft: px2dp(16) * 2,
    borderColor: '#F5F5F5',
    borderWidth: px2dp(13)
  },
  avartRight: {
    // flex: 1,
    marginLeft: px2dp(24),
  },
  nameBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  noCertiBox: {
    width: px2dp(210),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    backgroundColor: splitLineColorLightGray,
    paddingHorizontal: px2dp(18),
    height: px2dp(44),
    borderRadius: px2dp(28),
    marginTop: px2dp(16)
  },
  certiPart: {
    borderRadius: px2dp(28),
    borderWidth: px2dp(1),
    borderColor: '#CDCCC9',
    marginTop: px2dp(16),
    paddingHorizontal: px2dp(18),
  },
  certiBox: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(44)
  },
  noCertiIcon: {
    width: px2dp(34),
    height: px2dp(34),
  },
  onCertiTxt: {
    fontSize: px2dp(30),
    color: '#E7B35B',
    marginLeft: px2dp(8),
  },
  busRightDown: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(8)
  },
  username: {
    fontSize: px2dp(36),
    color: '#343332',
    fontWeight: '700'
  },
  isManagerIcon: {
    width: px2dp(78),
    height: px2dp(32),
    marginLeft: px2dp(12)
  },
  isUserIcon: {
    width: px2dp(104),
    height: px2dp(40),
    marginLeft: px2dp(12)
  },
  isCertiIcon: {
    width: px2dp(32),
    height: px2dp(32),
    marginLeft: px2dp(12)
  },
  leftContent: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerRightBg: {
    width: px2dp(331),
    height: px2dp(276)
  },
  mt40: {
    marginTop: px2dp(24),
  },
  userBgImg: {
    width: screenWidth,
    height: px2dp(135),
    paddingHorizontal: px2dp(64),
    flexDirection: 'row',
    paddingTop: px2dp(28),
    marginTop: px2dp(60),
  },
  buildIngImg: {
    width: px2dp(34),
    height: px2dp(34),
  },
  enterpriseName: {
    color: fontColorCoffee,
    fontSize: px2dp(30),
    fontWeight: 'bold',
    marginLeft: px2dp(4),
  },
  headerDesc: {
    color: fontColorDeepGray,
    fontSize: px2dp(24),
    marginTop: px2dp(8)
  },
});
